/*
* pyy Inc.
* Copyright (c) 2019 All Rights Reserved.
* create by pengyangyan
* date:2019-02-28
*/
package com.cqjtu.platform.controller;

import com.cqjtu.platform.entity.UploadFile;
import com.cqjtu.platform.enums.ExceptionEnums;
import com.cqjtu.platform.exception.MyException;
import com.cqjtu.platform.service.UploadFileService;
import com.cqjtu.platform.utils.tools.QiniuApi;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;


/**
 * UploadFile 控制器
 * 
 * @author pengyangyan
 * Date: 2019-02-28 11:15:59
 */
@Slf4j
@Api(description = "文件上传接口")
@Controller
@RequestMapping(value = "api/uploadFile")
public class UploadFileController extends BaseController<UploadFileService,UploadFile,String> {

    @Value("${qiniu.ak}")
    private String accessKey;
    @Value("${qiniu.sk}")
    private String secretKey;
    @Value(("${qiniu.bucket}"))
    private String bucket;
    @Value(("${qiniu.url}"))
    private String url;


    @PostMapping("/upload")
    public ResponseEntity<String> upload(MultipartFile file) throws IOException {
        //        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String key = QiniuApi.writeName();

        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("上传成功，地址为：{}{}",url,putRet.key);
            UploadFile uploadFile = new UploadFile();
            uploadFile.setFilePath(url+key);
            uploadFile.setFileId(key);
            uploadFile.setOriginalFileName(file.getOriginalFilename());
            this.service.insert(uploadFile);
            return ResponseEntity.ok(uploadFile.getFileId());
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        throw new MyException(ExceptionEnums.UPLOAD_FAIL);
    }

    /**
     * 删除服务器的图片
     * @param key
     */
    private void deleteFile(String key){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }


    @Override
    @GetMapping(value = "delete/{id}")
    public ResponseEntity<String> delete(@PathVariable("id")String id) {
        ResponseEntity<String> delete = super.delete(id);
        deleteFile(id);
        return delete;
    }
}
